<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基础信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="证书种类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="certificateType">
                  <j-dict-select-tag @input="cerChangeValue" :disabled="formDisabled" type="list" v-model="model.certificateType" dictCode="certificate_type" placeholder="请选择证书种类" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.certificateType==4">
                <a-form-model-item label="专利分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="patentType">
                  <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.patentType" dictCode="patent_type" placeholder="请选择专利分类" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="证书名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="certificateName">
                  <!-- <a-input :disabled="formDisabled" v-model="model.certificateName" placeholder="请输入证书名称" :maxLength="100"></a-input> -->
                  <a-select
                    :getPopupContainer="(node) => node.parentNode"
                    showSearch
                    :disabled="formDisabled || !model.certificateType"
                    placeholder="请选择证书名称"
                    style="width: 100%"
                    @change="changeName"
                    :filterOption="filterOption"
                    v-model="model.certificateName"
                    allowClear
                  >
                    <a-select-option v-for="d in dataOptions" :key="d.id" :value="d.id">{{ d.certName }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="发证单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="issueCertificateUnit">
                  <a-input :disabled="formDisabled" :maxLength="100" v-model="model.issueCertificateUnit" placeholder="请输入发证单位"></a-input>            
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="发证日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="issueCertificateDate">
                  <j-date
                    placeholder="请选择发证日期"
                    v-model="model.issueCertificateDate"
                    :show-time="false"
                    date-format="YYYY-MM-DD"
                    :disabled="formDisabled"
                    style="width: 100%"
                  />         
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="长期有效" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isAlways">
                  <j-dict-select-tag @input="isAlwaysChangeValue" type="radio" dictCode="YES_OR_NO" :disabled="formDisabled" v-model="model.isAlways" placeholder="请选择是否长期有效" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" :hidden="model.isAlways==1">
                <a-form-model-item label="有效期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="validPeriod">
                  <j-date
                    placeholder="请选择有效期"
                    v-model="model.validPeriod"
                    :show-time="false"
                    date-format="YYYY-MM-DD"
                    :disabled="formDisabled"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="原件保管员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="custodian">
                  <a-input :disabled="formDisabled" :maxLength="30" v-model="model.custodian" placeholder="请输入原件保管员"></a-input>            
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachments">
                  <j-upload v-if="!waterPdisable" :disabled="formDisabled" v-model="model.attachments" :showToast="false" fileFormat=".pdf, .PDF" isSingle></j-upload>
                  <view-upload v-else disabled v-model="model.attachments"></view-upload>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="详细信息">
            <a-row :gutter="48">
              <a-col :span="24" v-for="item in detailData" :key="item.id">
                <a-form-model-item :label="item.certField" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-textarea :autosize="{ minRows: 2, maxRows: 10 }" :disabled="formDisabled" :max-length="1000" v-model="item.fieldContent" placeholder="请输入"></a-textarea>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
  import { getAction } from '@/api/manage'
  import ViewUpload from '@/views/components/ViewUpload.vue'
  export default {
    name: 'ErpCertificationChildForm',
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      // 是否添加水印
      waterPdisable: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    components: { ViewUpload },
    data () {
      return {
        model:{
          certFieldList: []
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
          certificateName: [{ required: true, message: '请输入证书名称!', trigger: 'blur' }],
          issueCertificateUnit: [{ required: true, message: '请输入发证单位!', trigger: 'blur' }],
          certificateType: [{ required: true, message: '请选择证书种类!', trigger: ['change', 'blur'] }],
          issueCertificateDate: [{ required: true, message: '请选择发证日期!', trigger: ['change', 'blur'] }],
          isAlways: [{ required: true, message: '请选择是否长期有效!', trigger: ['change', 'blur'] }],
          validPeriod: [{ required: true, message: '请选择有效期!', trigger: ['change', 'blur'] }],
          attachments: [{ required: true, message: '请选择附件!', trigger: ['change', 'blur'] }],
          custodian: [{ required: true, message: '请输入原件保管员!', trigger: 'blur' }],
        },
        url: {
          add: "/api/erp/act/erpActQuitConfig/add",
          edit: "/api/erp/act/erpActQuitConfig/edit",
          queryById: "/api/erp/act/erpActQuitConfig/queryById"
        },
        flag: false,
        activeKey: ['1','2'],
        detailData: [],
        dataOptions: [],
        parentSource: []
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      async changeName(val){
        let res = await getAction('/api/erp/basecertinfo/field/fields',{ parentId: val })
        if(res.success && res.result){
          this.detailData = res.result.map(v => {
            return {
              fieldId: v.fieldId,
              fieldContent: v.fieldContent,
              certField: v.certField,
              fieldContentId: v.fieldContentId
            }
          })
        } else {
          this.detailData = []
        }
      },
      async changeNames(val,certId){
        let res = await getAction('/api/erp/basecertinfo/field/fields',{ parentId: val,certId })
        if(res.success && res.result){
          this.detailData = res.result.map(v => {
            return {
              fieldId: v.fieldId,
              fieldContent: v.fieldContent,
              certField: v.certField,
              fieldContentId: v.fieldContentId
            }
          })
        } else {
          this.detailData = []
        }
      },
      async getCertificateName(typeCode){
        let res = await getAction('/api/erp/basecertinfo/field/nameList',{ typeCode })
        if(res.success){
          this.dataOptions = res.result || []
        }
      },
      cerChangeValue(val,flag){
        if(val==4){
          this.$set(this.validatorRules,'patentType',[{ required: true, message: '请选择专利分类!', trigger: ['change', 'blur'] }])
        } else {
          this.$delete(this.validatorRules,'patentType')
          this.$set(this.model,'patentType','')
        }
        if(flag!='1'){
          this.$set(this.model,'certificateName',undefined)
          this.detailData = []
        }
        this.getCertificateName(val)
      },
      isAlwaysChangeValue(val){
        if(val==0){
          this.$set(this.validatorRules,'validPeriod',[{ required: true, message: '请选择有效期!', trigger: ['change', 'blur'] }])
        } else {
          this.$set(this.validatorRules,'validPeriod',[{ required: false }])
          this.$set(this.model,'validPeriod','')
        }
      },
      add (data) {
        this.edit(this.modelDefault,data);
      },
      edit (record,data) {
        this.parentSource = data
        this.$refs.form.clearValidate();
        this.model = Object.assign({}, record);
        this.isAlwaysChangeValue(this.model.isAlways)
        this.cerChangeValue(this.model.certificateType,'1')
        if(record.certFieldList && record.certFieldList.length){
          this.detailData = record.certFieldList.map(v => {
            return {
              fieldId: v.fieldId,
              fieldContent: v.fieldContent,
              certField: v.certField,
              fieldContentId: v.fieldContentId
            }
          })
        } else {
          if(record.id){
            this.changeNames(record.certificateName,record.id)
          } else {
            this.detailData = []
          }
        }
        this.visible = true;
      },
      submitForm () {
        const that = this;
        let source = JSON.parse(JSON.stringify(this.parentSource))
        if(this.model.id || this.model.key || this.model.key==0){
          source.splice(this.model.key, 1, this.model);
          if(source.filter(v => v.certificateName==this.model.certificateName).length>1){
            this.$message.warning('请重新选择证书名称!')
            this.$emit('unButtonDisable')
            return
          }
        } else {
          if(source.filter(v => v.certificateName==this.model.certificateName).length>0){
            this.$message.warning('请重新选择证书名称!')
            this.$emit('unButtonDisable')
            return
          }
        }
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            this.$set(this.model,'certFieldList',this.detailData)
            that.$emit('ok', this.model, this.flag);
          } 
        })
        this.$emit('unButtonDisable')
      },
    }
  }
</script>
